//
//  ByShopProductDetailSkuVC.m
//  hutouben_ios
//
//  Created by pro on 16/11/30.
//  Copyright © 2016年 mc. All rights reserved.
//

#import "ByUIProductDetailSkuSelectVC.h"

// view
#import "ByViewDetailSkuInfo.h"             // 规格选择的信息视图
#import "ByViewDetailSkuCollection.h"       // 规格列表视图
#import "ByViewItemForCollection.h"         // 规格列表视图的cell item

// model
#import "SkuModel.h"                        // 商品的规格model
#import "SkuIdModel.h"                      // 商品的规格idModel，用于检索规格
#import "SkuNameModel.h"                    // 商品的规格nameModel，用于展示名称

// handle
#import "ProductInfoHandle.h"

@interface ByUIProductDetailSkuSelectVC () <ByProductSkuCollectionViewDataSource>

// 列表视图
@property (nonatomic, strong) ByViewDetailSkuInfo       *infoView;
@property (nonatomic, strong) ByViewDetailSkuCollection *collect;

// 模型数据
@property (nonatomic, strong) NSArray<SkuModel *>       *skuAry;
@property (nonatomic, strong) NSArray<SkuIdModel *>     *skuIdAry;
@property (nonatomic, strong) NSArray<SkuNameModel *>   *skuNameAry;

// ????
@property (nonatomic, copy) NSArray *items1;
@property (nonatomic, copy) NSArray *items2;

@end

@implementation ByUIProductDetailSkuSelectVC
{
    NSMutableArray  *_skuSelectRecordModelArray;    // 记录每组中选中的数组
    NSMutableArray  *_skuSelectIdArray;             // 记录每组中选中model的id的数组
    NSInteger        _selectCount;                  // 记录当前选择的数量
    SkuModel        *_selectedModel;                // 记录当前选中的model
}

// 数据设置
// 规格内容数组
- (void)setSkuNameAry:(NSArray<SkuNameModel *> *)skuNameAry {
    
    _skuNameAry = skuNameAry;
    
    // 这种情况下，表示统一规格，则选中model默认是规格model列表中的第一个
    if (_skuNameAry.count == 0) {
        _selectedModel = [_skuAry firstObject];
        return;
    }
    
    // 初始化记录数组和其中的recordModel
    _skuSelectRecordModelArray = [[NSMutableArray alloc] init];
    
    for (int i = 0;  i < _skuNameAry.count; i ++) {
        
        ByModelSkuSelectRecord *recordModel = [[ByModelSkuSelectRecord alloc] init];
        SkuNameModel *skuNameModel = _skuNameAry[i];
        recordModel.rowCount = skuNameModel.vidAry_des.count;
        recordModel.currentSection = i;
        [_skuSelectRecordModelArray addObject:recordModel];
    }
        
}
// 规格id数组
- (void)setSkuIdAry:(NSArray<SkuIdModel *> *)skuIdAry {
    
    _skuIdAry = skuIdAry;
    
    _skuSelectIdArray = [[NSMutableArray alloc] init];
    
    for (int i = 0;  i < _skuIdAry.count; i ++) {
        
        NSString *keyId = [ProductInfoHandle getDefaultNoIDString];
        [_skuSelectIdArray addObject:keyId];
    }
    
}
// 规格列表数组
- (void)setSkuAry:(NSArray<SkuModel *> *)skuAry {
    
    _skuAry = skuAry;
}
// 商品详情
- (void)setDetailModel:(ByModelProductDetail *)detailModel {
    
    _detailModel = detailModel;
    
    self.skuAry     = _detailModel.skuAry;
    self.skuNameAry = _detailModel.skuNameAry;
    self.skuIdAry   = _detailModel.skuIdAry;
}


#pragma mark - view methods
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor clearColor];
    
    _selectCount = 1;   // 设置默认选择数量为1

    [self setupUI];     // 初始化UI（列表等）
}

- (void)setupUI {
    
    self.infoView = [[ByViewDetailSkuInfo alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 120)];
    [self.view addSubview:self.infoView];
    self.infoView.unSelectedModel = self.detailModel;
    __weak typeof(self) weakself = self;
    self.infoView.closeBlock = ^ {
        [weakself dismissViewControllerAnimated:YES completion:nil];
    };
    
    // 创建列表
    self.collect = [[ByViewDetailSkuCollection alloc] initWithFrame:CGRectMake(0, self.infoView.bottom, self.view.width, SCREEN_HEIGHT - 200 - 40 - self.infoView.height)];
    if (_selectedModel) {
        self.collect.price = _selectedModel.price;
    } else {
        self.collect.price = [NSString stringWithFormat:@"%@", _detailModel.price];
    }
    self.collect.dataSource = self;
    [self.view addSubview:self.collect];
    
    // 设置按钮
    [self setupButton];
}
- (void)setupButton {

    switch (self.enterStatus) {
        case 0:
        {
            UIButton *okButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
            okButton1.frame = CGRectMake(0, 0, self.view.width / 2, 40);
            okButton1.backgroundColor = rgba(251, 128, 10, 1);
            [okButton1 setTitle:@"加入购物车" forState:UIControlStateNormal];
            [okButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [okButton1 addTarget:self action:@selector(okAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:okButton1];
            okButton1.bottom = SCREEN_HEIGHT - 200;
            
            UIButton *okButton2 = [UIButton buttonWithType:UIButtonTypeCustom];
            okButton2.frame = CGRectMake(okButton1.right, 0, self.view.width / 2, 40);
            okButton2.backgroundColor = rgba(250, 56, 9, 1);
            [okButton2 setTitle:@"立即购买" forState:UIControlStateNormal];
            [okButton2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [okButton2 addTarget:self action:@selector(okAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:okButton2];
            okButton2.bottom = SCREEN_HEIGHT - 200;
        }
            break;
        case 1:
        {
            UIButton *okButton = [UIButton buttonWithType:UIButtonTypeCustom];
            okButton.frame = CGRectMake(0, 0, self.view.width, 40);
            okButton.backgroundColor = rgba(251, 128, 10, 1);
            [okButton setTitle:@"加入购物车" forState:UIControlStateNormal];
            [okButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [okButton addTarget:self action:@selector(okAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:okButton];
            okButton.bottom = SCREEN_HEIGHT - 200;
        }
            break;
        case 2:
        {
            UIButton *okButton = [UIButton buttonWithType:UIButtonTypeCustom];
            okButton.frame = CGRectMake(0, 0, self.view.width, 40);
            okButton.backgroundColor = rgba(250, 56, 9, 1);
            [okButton setTitle:@"立即购买" forState:UIControlStateNormal];
            [okButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [okButton addTarget:self action:@selector(okAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:okButton];
            okButton.bottom = SCREEN_HEIGHT - 200;
        }
            break;
        default:
            break;
    }
}

#pragma mark - dataSource 
// 设置组数
- (NSInteger)numOfSections:(ByViewDetailSkuCollection *)collectionView {
    
    return _skuNameAry.count;
}

// 设置每次的item数
- (NSInteger)numOfItems:(ByViewDetailSkuCollection *)collectionView inSection:(NSInteger)section {
    
    SkuNameModel *model = _skuNameAry[section];
    return model.vidAry_des.count;    
}

// 设置每组的标题（即每种规格的标题）
- (NSString *)collectionView:(ByViewDetailSkuCollection *)collectionView titleInSection:(NSInteger)section {
    
    SkuNameModel *model = _skuNameAry[section];
    return model.sid_des;
}

// 调用数量修改的回调
- (void)collectionView:(ByViewDetailSkuCollection *)collectionView didModifyCount:(NSInteger (^)())modify {
    
    _selectCount = modify();
}

// 设置没个item的视图展示
- (UIView *)collectionView:(ByViewDetailSkuCollection *)collectionView viewAtIndexPath:(NSIndexPath *)indexPath {
    
    ByViewItemForCollection *cell = [[ByViewItemForCollection alloc] init];
    CGSize size = [self collectionView:collectionView sizeForviewAtIndexPath:indexPath];
    cell.labelSort.frame = CGRectMake(0, 0, size.width, size.height);
    
    // 1.数据展示
    SkuNameModel *model = _skuNameAry[indexPath.section];
    NSString *text = model.vidAry_des[indexPath.row];
    cell.labelSort.text = text;
    
    // 2.collection颜色变化
    // 选择中模型
    ByModelSkuSelectRecord *recordModel = _skuSelectRecordModelArray[indexPath.section];
    cell.tag = indexPath.row;
    cell.userInteractionEnabled = YES;
    
    // 获得该row的单元格是否可点击
    BOOL isAble = [recordModel.isableTouchCollectArray[indexPath.row] boolValue];
    if (!isAble) {
        cell.userInteractionEnabled = NO; // 不可点击的单元格做处理
    }
    
    // 3.cell处理（单元格背景颜色和字体颜色变化）
    [cell showSelectCollectionRow:recordModel];
    
    return cell;
}
// 设置每个item的size
- (CGSize)collectionView:(ByViewDetailSkuCollection *)collectionView sizeForviewAtIndexPath:(NSIndexPath *)indexPath {
    
    SkuNameModel *model = _skuNameAry[indexPath.section];

    return CGSizeMake([model.vidAry_des[indexPath.item] getSizeOfString:14].width + 20, 30);
}
// 设置每个item的点击事件
- (void)collectionView:(ByViewDetailSkuCollection *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    // 判断当前点击的item是否能可以点击
    ByModelSkuSelectRecord *recordModel = _skuSelectRecordModelArray[indexPath.section];
    BOOL isAble = [recordModel.isableTouchCollectArray[indexPath.row] boolValue];
    
    // 不能点击，则直接返回
    if (!isAble) {
        return;
    } else {
        // 初始化 _skuSelectModelArray ，使 bool为YES，然后再判断赋值
        for (NSInteger i = 0  ; i < _skuSelectRecordModelArray.count; i ++) {
            ByModelSkuSelectRecord *recordModel = [_skuSelectRecordModelArray objectAtIndex:i];
            
            [recordModel changeStateOfTouchCollectArray:YES];
        }
    }
    
    // **** 记录当前collection的选择状态（SkuCellSelectModel），为后面刷新collecView时规格状态改变铺路  ***
    NSString *idStr = nil;
    // 如果点击的是同一个item则设置该item为未点击状态
    if (recordModel.selectRow == indexPath.row) {
        recordModel.selectRow = -1;
        recordModel.selectSection = -1;

        // 把idStr设置为默认的（未选中的）
        idStr = [ProductInfoHandle getDefaultNoIDString];
        
    } else {

        recordModel.selectRow = indexPath.row;
        recordModel.selectSection = indexPath.section;
        // 刷新
        //        [recordModel reloadSelectRow:indexPath.row section:indexPath.section];

        // 获得当前点击的row的idStr
        idStr = [ProductInfoHandle getCurrCollectSkuId:indexPath skuIdModel:_skuIdAry[indexPath.section]];

    }
    
    // 2.改变保存的skuKeyID
    [_skuSelectIdArray replaceObjectAtIndex:indexPath.section withObject:idStr];
    
    // 3.做判断，选择是否合法（是否可以组成完成的sku_id）
    [ProductInfoHandle isUseableSkuIdArray:_skuSelectIdArray complete:^(BOOL isable) {
        
        // 每种规格都已经选择，开始查找是否存在选择的模型
        if (isable) {
            
            // 去掉当前选择的组的另外的组
            NSArray *selectedIdArray = [ProductInfoHandle getSelectSkuIDList:_skuSelectIdArray except:indexPath.section];
            
            // 预测当前点击的组中可点击的单元格
            [self checkAllowTouchesForTheSection:indexPath.section withSkuSelectedArray:selectedIdArray];
            
            // 根据规格ID找到对应商品
            SkuModel *model = [self getSelectSkuModel];
            if (model != nil ) {  //展示商品详情信息
                
                // 找到了正确的商品
                _selectedModel = model;
            }
            // 如果没有找到，或者库存为0，都要把当前sku_id,改掉
            if (model == nil || [model.quantity boolValue] == 0) {
                
                [_skuSelectIdArray replaceObjectAtIndex:indexPath.section withObject:[ProductInfoHandle getDefaultNoIDString]];
                
                ByModelSkuSelectRecord *recordModel = _skuSelectRecordModelArray[indexPath.section];
                [recordModel reloadSelectRow:-1 section:indexPath.section];
                
                // 该商品库存为0
                _selectedModel = nil;
            }
        }
        //返回还没有被选择的分区下标:"0" "1",
    } noSelectAry:^(NSArray *notSeletSectionArray) {
        
        // 如果只有一个分区没有被选中
        if (notSeletSectionArray.count == 1) {
            
            // selectedSkuIdAry:是除了未赋值的所有skuId的数组
            // 而_skuSelectIdArray是包含了未赋值的所有的skuId的数组
            NSArray *selectedSkuIdAry = [ProductInfoHandle getSelectedSkuIdAry:_skuSelectIdArray];
            
            // 获得没被选择的组的索引（section）
            NSInteger section = [[notSeletSectionArray lastObject] integerValue];
            
            [self checkAllowTouchesForTheSection:section withSkuSelectedArray:selectedSkuIdAry];

        }
                
        // 没有选择全部的规格
        _selectedModel = nil;
    }];
    
    // TODO: 选中的skuid数组（1：3，2：4），可以拼接成sku_id（1：3；2：4；）然后可以获得详细的商品
    NSLog(@"****keyIdAry*****:%@ \n选中的商品sku_id:%@", _skuSelectIdArray, _selectedModel.sku_id);
    //5 刷新
    if (_selectedModel) {
        
        self.infoView.selectedModel = _selectedModel;
    } else {
        self.infoView.selectedModel = nil;
    }
    [_collect reloadData];

}


#pragma mark - 点击事件
- (void)okAction:(UIButton *)sender {
    
    if (!_selectedModel) {
        [ByCoreToolAlert showFailureWithText:@"请选择规格"];
        return;
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if ([sender.titleLabel.text isEqualToString:@"加入购物车"]) {
        self.addAction(_selectedModel, _selectCount, 1);
    } else {
        self.addAction(_selectedModel, _selectCount, 2);
    }
}

#pragma mark - 其他方法（代码太多，写成代码块方法）
// 根据选中的id字符串 找到对应的商品
- (SkuModel *)getSelectSkuModel {
    
    NSString *fullSkuId = [ProductInfoHandle getFullSkuId:_skuSelectIdArray];
    //根据sku_id 找规格模型
    SkuModel *model = [ProductInfoHandle findSkuModelInSkuAry:_detailModel.skuAry fullSkuId:fullSkuId];
    
    return model;
}

// 查找某组中可以点击的row数组
- (void)checkAllowTouchesForTheSection:(NSInteger )section withSkuSelectedArray:(NSArray *)selectedSkuIdAry {
    
    [ProductInfoHandle forecastSkuIdIsable:_detailModel selectedSkuIdAry:selectedSkuIdAry section:section ableBlock:^(NSArray *ableTouchSkuIDArray) {
        
        // 获得该组对应的规格选择模型（用于重置可选数组）
        ByModelSkuSelectRecord *recordModel = [_skuSelectRecordModelArray objectAtIndex:section];
        
        // 如果可选数组为空，则该组的单元格全部不可选
        if (ableTouchSkuIDArray.count == 0 || ableTouchSkuIDArray == nil) {
            
            [recordModel changeStateOfTouchCollectArray:NO];
        } else {
            
            SkuIdModel *model = _skuIdAry[section];

            [recordModel changeStateOfTouchCollectArray:NO];
            for (NSString *key in ableTouchSkuIDArray) {
                NSInteger index = [model getKeyValueIndex:key];
                [recordModel.isableTouchCollectArray replaceObjectAtIndex:index withObject:@YES];
            }
        }
    }];
}


@end
